package SparkStream

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.{Seconds, StreamingContext}

import java.util

object Producerspark {
  def main(args: Array[String]): Unit = {

    // Spark conf
    val conf = new SparkConf().setMaster("local[*]").setAppName("Spark Kafka Consumer") //local[*]表示本地有多少资源用多少资源
    //进行流式处理，微批次处理，间隔时间2秒
    val ssc = new StreamingContext(conf, Seconds(2)) //要到依赖
    ssc.sparkContext.setLogLevel("error")
    //配置broker,key,value,groupid,
    val kakaParams = Map[String, Object](
      "bootstrap.servers" -> "123.56.187.176:9092", //123.56.187.176
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "niit",
      "enable.auto.commit" -> (false: java.lang.Boolean),
    )

    val topicName = Array("stuInfo")
    val streamRdd = KafkaUtils.createDirectStream[String, String](
      ssc, PreferConsistent,
      Subscribe[String, String](topicName, kakaParams)
    )

    //  producer 配置项
    val property = new util.HashMap[String, Object]()
    property.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.134.128:9092")
    property.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
    property.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")

    //时间窗口
    val res = streamRdd.map(_.value())
    val result = res.flatMap(_.split("\t")).map((_, 1)).reduceByKeyAndWindow(_ + _, Seconds(4), Seconds(4))
    result.foreachRDD(
      x => {
        println("--------------数据是--------------")
        x.foreach(
          obj => {
            println(obj)

            //连接新的客户端
            val producer = new KafkaProducer[String, String](property)
            //把数据发送,spark链接kafka
            producer.send(new ProducerRecord[String, String]("test", obj.toString))
          }
        )
      }
    )

    //producer配置项
    //开始scc
    ssc.start()
    ssc.awaitTermination() //监控
  }


}
